package com.tssf.car_manage.service.impl;

import com.tssf.car_manage.entity.Customer;
import com.tssf.car_manage.mapper.CustomerMapper;
import com.tssf.car_manage.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustomerServiceImpl implements CustomerService {

    private final CustomerMapper customerMapper;

    @Autowired
    public CustomerServiceImpl(CustomerMapper customerMapper) {
        this.customerMapper = customerMapper;
    }

    @Override
    public List<Customer> findAll() {
        return customerMapper.findAll();
    }

    @Override
    public Customer findById(Integer id) {
        return customerMapper.findById(id);
    }

    @Override
    public int save(Customer customer) {
        if (customer.getCustomer_id() == null) {
            return customerMapper.insert(customer);
        } else {
            return customerMapper.update(customer);
        }
    }

    @Override
    public int delete(Integer id) {
        return customerMapper.delete(id);
    }

    @Override
    public int count() {
        return customerMapper.count();
    }

    @Override
    public int update(Customer customer) {
        // 参数校验
        if (customer.getCustomer_id() == null) {
            throw new IllegalArgumentException("客户ID不能为空");
        }

        // 检查客户是否存在
        Customer existing = customerMapper.findById(customer.getCustomer_id());
        if (existing == null) {
            throw new IllegalArgumentException("客户不存在，ID: " + customer.getCustomer_id());
        }

        // 执行更新
        int affectedRows = customerMapper.update(customer);

        if (affectedRows == 0) {
            throw new RuntimeException("客户更新失败，可能数据未变化");
        }

        return affectedRows;
    }
    @Override
    public List<Customer> searchByNameOrPhone(String keyword) {
        return customerMapper.searchByNameOrPhone(keyword);
    }
}